package com.digua.iot.confignetwork.ui

import android.os.Bundle
import com.blankj.utilcode.util.CacheDiskUtils
import com.blankj.utilcode.util.CacheDoubleUtils
import com.blankj.utilcode.util.CacheMemoryUtils
import com.blankj.utilcode.util.NetworkUtils
import com.digua.base.base.DefDialog
import com.digua.base.dialog.LoadingDialog
import com.digua.base.util.AppUtil
import com.digua.base.util.LogUtil
import com.digua.base.util.SPUtils
import com.digua.base.util.StrUtil
import com.digua.base.util.Toasts
import com.digua.base.util.ViewUtil
import com.digua.iot.confignetwork.base.BaseActivity
import com.digua.iot.confignetwork.config.Const
import com.digua.iot.confignetwork.databinding.ActivityMainBinding


class MainActivity : BaseActivity<ActivityMainBinding>() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initUI()
        initData()
    }

    private fun initUI() {
        ui.config.setOnClickListener {
            if (!NetworkUtils.isWifiConnected()) {
                Toasts.showLong("wifi未连接，请先连接wifi")
                return@setOnClickListener
            }
            if (NetworkUtils.is5G()) {
                Toasts.showLong("请连接2.4G网络")
                return@setOnClickListener
            }
            val wifiName = ViewUtil.getVal(ui.wifiName)
            val wifiPwd = ViewUtil.getVal(ui.wifiPwd, "")
            if (StrUtil.isBlank(wifiName)) {
                Toasts.showLong("网络不存在")
                return@setOnClickListener
            }
            if (StrUtil.isBlank(wifiPwd)) {
                Toasts.showLong("请输入密码")
                return@setOnClickListener
            }
            wifiInfo.pwd = wifiPwd
            SPUtils.put(Const.SP_HISTORYWIFI + wifiInfo.ssid, wifiPwd!!)

            LoadingDialog.show(true, "配置中...").setOnDismissListener { cancelConfig() }
            onConfig { isSuccess, msg ->
                LoadingDialog.dismiss()
                LogUtil.e("======>>>isSuccess = ${isSuccess}; msg = ${msg}")
                val dialog = DefDialog()
                dialog.message = msg
                dialog.show(supportFragmentManager)
            }
        }
    }

    private fun initData() {
        getWifiInfo {
            clearCache()
            ui.wifiName.setText(it.ssid)
            ui.wifiPwd.setText(it.pwd)
        }
    }

    override fun onResume() {
        super.onResume()
        clearCache()
        initData()
    }

    /**
     * 网络断开
     */
    override fun onDisconnected() {
        initData()
    }

    /**
     * 网络连接
     */
    override fun onConnected(networkType: NetworkUtils.NetworkType) {
        initData()
    }

    private fun clearCache() {
        CacheMemoryUtils.getInstance().clear()
        CacheDoubleUtils.getInstance().clear()
        CacheDiskUtils.getInstance().clear()
        AppUtil.cleanGarbage()
        System.gc()
    }
}